package com.wondream.myframework.io;

import java.io.IOException;
import java.io.RandomAccessFile;

public class RandomAccessFileTest {

    public static void main(String[] args) {
        RandomAccessFile randomAccessFile = null;
        try {
            randomAccessFile = new RandomAccessFile("./logs/data.txt", "rw");
            long fileLength = randomAccessFile.length();
            randomAccessFile.skipBytes((int)fileLength);
            int i = Integer.MAX_VALUE;
            randomAccessFile.write(i>>>24);
            randomAccessFile.write(i>>>16);
            randomAccessFile.write(i>>>8);
            randomAccessFile.write(i);
            String data = "hello123优秀";
            randomAccessFile.write(data.getBytes());
            fileLength = randomAccessFile.length();
            System.out.println(fileLength);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(randomAccessFile!=null){
                try {
                    randomAccessFile.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                randomAccessFile = null;
            }
        }
    }


    public static void testRead(){
        RandomAccessFile randomAccessFile = null;
        try {
            randomAccessFile = new RandomAccessFile("./logs/data.txt", "rw");
            int bufferLen = 1024*100;
            byte[] data = new byte[bufferLen];
            while (randomAccessFile.read(data, 0, bufferLen)!=-1){
                System.out.println(new String(data, "UTF-8"));
            }
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            if(randomAccessFile!=null){
                try {
                    randomAccessFile.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                randomAccessFile = null;
            }
        }
    }

}
